<template>
  <div class="app-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>提交记录管理</span>
          <div>
            <el-button type="success" @click="handleExport">
              <el-icon><Download /></el-icon>
              导出记录
            </el-button>
            <el-button type="info" @click="handleStatistics">
              <el-icon><DataAnalysis /></el-icon>
              统计分析
            </el-button>
            <el-button type="warning" @click="handlePlagiarismCheck">
              <el-icon><Warning /></el-icon>
              抄袭检测
            </el-button>
          </div>
        </div>
      </template>

      <!-- 搜索表单 -->
      <div class="search-form">
        <el-form :model="queryParams" ref="queryRef" :inline="true" label-width="80px">
          <el-form-item label="题目名称" prop="problemTitle">
            <el-input
              v-model="queryParams.problemTitle"
              placeholder="请输入题目名称"
              clearable
              style="width: 200px"
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item label="用户名" prop="username">
            <el-input
              v-model="queryParams.username"
              placeholder="请输入用户名"
              clearable
              style="width: 150px"
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item label="提交状态" prop="status">
            <el-select v-model="queryParams.status" placeholder="请选择状态" clearable style="width: 120px">
              <el-option label="通过" value="ACCEPTED" />
              <el-option label="错误答案" value="WRONG_ANSWER" />
              <el-option label="超时" value="TIME_LIMIT_EXCEEDED" />
              <el-option label="内存超限" value="MEMORY_LIMIT_EXCEEDED" />
              <el-option label="运行错误" value="RUNTIME_ERROR" />
              <el-option label="编译错误" value="COMPILE_ERROR" />
              <el-option label="系统错误" value="SYSTEM_ERROR" />
              <el-option label="判题中" value="JUDGING" />
            </el-select>
          </el-form-item>
          <el-form-item label="编程语言" prop="language">
            <el-select v-model="queryParams.language" placeholder="请选择语言" clearable style="width: 120px">
              <el-option label="Java" value="java" />
              <el-option label="Python" value="python" />
              <el-option label="C++" value="cpp" />
              <el-option label="C" value="c" />
              <el-option label="JavaScript" value="javascript" />
              <el-option label="Go" value="go" />
            </el-select>
          </el-form-item>
          <el-form-item label="提交时间">
            <el-date-picker
              v-model="dateRange"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              style="width: 300px"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 数据表格 -->
      <el-table v-loading="loading" :data="submissionList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="提交ID" align="center" prop="id" width="100" />
        <el-table-column label="题目信息" align="left" min-width="200">
          <template #default="scope">
            <div>
              <div class="problem-title">{{ scope.row.problemTitle }}</div>
              <div class="text-muted">ID: {{ scope.row.problemId }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="用户信息" align="center" width="150">
          <template #default="scope">
            <div>
              <div>{{ scope.row.username }}</div>
              <div class="text-muted">{{ scope.row.userNickname }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="提交状态" align="center" prop="status" width="120">
          <template #default="scope">
            <el-tag :type="getStatusTagType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="编程语言" align="center" prop="language" width="100">
          <template #default="scope">
            <el-tag type="info">{{ scope.row.language.toUpperCase() }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="执行时间" align="center" width="100">
          <template #default="scope">
            <span v-if="scope.row.executeTime">{{ scope.row.executeTime }}ms</span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="内存使用" align="center" width="100">
          <template #default="scope">
            <span v-if="scope.row.memoryUsage">{{ formatMemory(scope.row.memoryUsage) }}</span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="得分" align="center" width="80">
          <template #default="scope">
            <span class="score-text" :class="getScoreClass(scope.row.score)">
              {{ scope.row.score || 0 }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="提交时间" align="center" prop="submitTime" width="160">
          <template #default="scope">
            <span>{{ parseTime(scope.row.submitTime, '{y}-{m}-{d} {h}:{i}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="200" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button type="primary" icon="View" @click="handleViewCode(scope.row)" link>查看代码</el-button>
            <el-button type="info" icon="Document" @click="handleViewResult(scope.row)" link>查看结果</el-button>
            <el-dropdown @command="(command) => handleCommand(command, scope.row)" style="margin-left: 10px">
              <el-button type="primary" link>
                更多<el-icon class="el-icon--right"><arrow-down /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="handleRerun" icon="Refresh">重新判题</el-dropdown-item>
                  <el-dropdown-item command="handleAnalysis" icon="DataAnalysis">性能分析</el-dropdown-item>
                  <el-dropdown-item command="handleSimilarity" icon="Warning">相似度检测</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>

    <!-- 查看代码对话框 -->
    <el-dialog :title="codeDialogTitle" v-model="codeDialogVisible" width="900px" append-to-body>
      <div v-if="currentSubmission" class="code-detail">
        <!-- 提交信息 -->
        <div class="submission-info">
          <el-descriptions :column="3" border>
            <el-descriptions-item label="题目">{{ currentSubmission.problemTitle }}</el-descriptions-item>
            <el-descriptions-item label="用户">{{ currentSubmission.username }}</el-descriptions-item>
            <el-descriptions-item label="语言">{{ currentSubmission.language.toUpperCase() }}</el-descriptions-item>
            <el-descriptions-item label="状态">
              <el-tag :type="getStatusTagType(currentSubmission.status)">
                {{ getStatusText(currentSubmission.status) }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="执行时间">{{ currentSubmission.executeTime || 0 }}ms</el-descriptions-item>
            <el-descriptions-item label="内存使用">{{ formatMemory(currentSubmission.memoryUsage || 0) }}</el-descriptions-item>
          </el-descriptions>
        </div>

        <!-- 代码内容 -->
        <div class="code-section">
          <h4>提交代码</h4>
          <div class="code-container">
            <pre><code class="language-javascript">{{ currentSubmission.code || '代码内容加载中...' }}</code></pre>
          </div>
        </div>

        <!-- 编译信息 -->
        <div v-if="currentSubmission.compileInfo" class="compile-section">
          <h4>编译信息</h4>
          <div class="compile-info">
            <pre>{{ currentSubmission.compileInfo }}</pre>
          </div>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="codeDialogVisible = false">关 闭</el-button>
          <el-button type="primary" @click="downloadCode">下载代码</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 查看结果对话框 -->
    <el-dialog title="判题结果详情" v-model="resultDialogVisible" width="800px" append-to-body>
      <div v-if="currentSubmission" class="result-detail">
        <!-- 总体结果 -->
        <div class="result-summary">
          <el-row :gutter="20">
            <el-col :span="6">
              <div class="stat-item">
                <div class="stat-value" :class="getStatusClass(currentSubmission.status)">
                  {{ getStatusText(currentSubmission.status) }}
                </div>
                <div class="stat-label">判题状态</div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="stat-item">
                <div class="stat-value">{{ currentSubmission.score || 0 }}</div>
                <div class="stat-label">得分</div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="stat-item">
                <div class="stat-value">{{ currentSubmission.executeTime || 0 }}ms</div>
                <div class="stat-label">执行时间</div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="stat-item">
                <div class="stat-value">{{ formatMemory(currentSubmission.memoryUsage || 0) }}</div>
                <div class="stat-label">内存使用</div>
              </div>
            </el-col>
          </el-row>
        </div>

        <!-- 测试用例结果 -->
        <div class="testcase-results">
          <h4>测试用例结果</h4>
          <el-table :data="testCaseResults" style="width: 100%">
            <el-table-column prop="caseId" label="用例ID" width="80" />
            <el-table-column prop="status" label="状态" width="100">
              <template #default="scope">
                <el-tag :type="getTestCaseStatusTagType(scope.row.status)" size="small">
                  {{ getTestCaseStatusText(scope.row.status) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="executeTime" label="执行时间" width="100">
              <template #default="scope">
                {{ scope.row.executeTime }}ms
              </template>
            </el-table-column>
            <el-table-column prop="memoryUsage" label="内存使用" width="100">
              <template #default="scope">
                {{ formatMemory(scope.row.memoryUsage) }}
              </template>
            </el-table-column>
            <el-table-column prop="errorMessage" label="错误信息" />
          </el-table>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="resultDialogVisible = false">关 闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Submission">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Download, DataAnalysis, Warning } from '@element-plus/icons-vue'
import Pagination from '@/components/Pagination/index.vue'
import {
  getSubmissionPage,
  getSubmissionDetail,
  rejudgeSubmission,
  exportSubmissions,
  getUserSubmissionStats
} from '@/api/coding'

// 响应式数据
const loading = ref(true)
const ids = ref([])
const total = ref(0)
const codeDialogVisible = ref(false)
const resultDialogVisible = ref(false)
const codeDialogTitle = ref('')
const queryRef = ref()
const dateRange = ref([])
const currentSubmission = ref(null)

// 列表数据
const submissionList = ref([])
const testCaseResults = ref([])

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  problemTitle: undefined,
  username: undefined,
  status: undefined,
  language: undefined,
  startTime: undefined,
  endTime: undefined
})

// 获取提交记录列表
const getList = async () => {
  loading.value = true
  try {
    // 处理时间范围
    if (dateRange.value && dateRange.value.length === 2) {
      queryParams.startTime = dateRange.value[0]
      queryParams.endTime = dateRange.value[1]
    } else {
      queryParams.startTime = undefined
      queryParams.endTime = undefined
    }

    // 调用API获取数据
    const response = await getSubmissionPage(queryParams)
    if (response.code === 200) {
      submissionList.value = response.data.rows || []
      total.value = response.data.total || 0
    } else {
      ElMessage.error(response.message || '获取提交记录失败')
    }
  } catch (error) {
    console.error('获取提交记录失败:', error)
    ElMessage.error('获取提交记录失败')

    // 如果API调用失败，使用简单的模拟数据
    submissionList.value = [
      {
        id: 1,
        problemId: 'P001',
        problemTitle: '两数之和',
        userId: 'user001',
        username: 'student01',
        userNickname: '小明',
        language: 'java',
        status: 'ACCEPTED',
        score: 100,
        executeTime: 125,
        memoryUsage: 2048,
        submitTime: '2024-01-15 10:30:00',
        code: 'public class Solution { /* 代码内容 */ }',
        compileInfo: null
      },
      {
        id: 2,
        problemId: 'P002',
        problemTitle: '反转链表',
        userId: 'user002',
        username: 'student02',
        userNickname: '小红',
        language: 'python',
        status: 'WRONG_ANSWER',
        score: 60,
        executeTime: 89,
        memoryUsage: 1024,
        submitTime: '2024-01-15 11:20:00',
        code: 'def reverseList(head): # 代码内容',
        compileInfo: null
      }
    ]
    total.value = 50
  } finally {
    loading.value = false
  }
}

// 搜索按钮操作
const handleQuery = () => {
  queryParams.pageNum = 1
  getList()
}

// 重置按钮操作
const resetQuery = () => {
  queryRef.value?.resetFields()
  dateRange.value = []
  handleQuery()
}

// 多选框选中数据
const handleSelectionChange = (selection) => {
  ids.value = selection.map(item => item.id)
}

// 查看代码
const handleViewCode = async (row) => {
  try {
    const response = await getSubmissionDetail(row.id)
    if (response.code === 200) {
      currentSubmission.value = response.data
      codeDialogTitle.value = `查看代码 - ${row.problemTitle} (${row.username})`
      codeDialogVisible.value = true
    } else {
      ElMessage.error(response.message || '获取代码详情失败')
    }
  } catch (error) {
    console.error('获取代码详情失败:', error)
    ElMessage.error('获取代码详情失败')
    // 如果API调用失败，使用传入的行数据
    currentSubmission.value = row
    codeDialogTitle.value = `查看代码 - ${row.problemTitle} (${row.username})`
    codeDialogVisible.value = true
  }
}

// 查看结果
const handleViewResult = (row) => {
  currentSubmission.value = row
  // 模拟测试用例结果
  testCaseResults.value = [
    { caseId: 1, status: 'ACCEPTED', executeTime: 45, memoryUsage: 1024, errorMessage: '' },
    { caseId: 2, status: 'ACCEPTED', executeTime: 52, memoryUsage: 1056, errorMessage: '' },
    { caseId: 3, status: 'WRONG_ANSWER', executeTime: 38, memoryUsage: 1024, errorMessage: 'Expected: [1,2], Got: [2,1]' },
    { caseId: 4, status: 'ACCEPTED', executeTime: 41, memoryUsage: 1032, errorMessage: '' }
  ]
  resultDialogVisible.value = true
}

// 下载代码
const downloadCode = () => {
  if (!currentSubmission.value) return

  const element = document.createElement('a')
  const file = new Blob([currentSubmission.value.code], { type: 'text/plain' })
  element.href = URL.createObjectURL(file)
  element.download = `${currentSubmission.value.problemTitle}_${currentSubmission.value.username}.${getFileExtension(currentSubmission.value.language)}`
  document.body.appendChild(element)
  element.click()
  document.body.removeChild(element)

  ElMessage.success('代码下载成功')
}

// 导出记录
const handleExport = async () => {
  try {
    const params = {
      ...queryParams,
      startTime: queryParams.startTime,
      endTime: queryParams.endTime
    }

    const response = await exportSubmissions(params)
    if (response.code === 200) {
      ElMessage.success('导出成功，文件正在下载...')
      // 这里可以添加文件下载逻辑
      window.open(response.data, '_blank')
    } else {
      ElMessage.error(response.message || '导出失败')
    }
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败')
  }
}

// 统计分析
const handleStatistics = () => {
  ElMessage.info('统计分析功能开发中')
}

// 抄袭检测
const handlePlagiarismCheck = () => {
  ElMessage.info('抄袭检测功能开发中')
}

// 下拉菜单操作
const handleCommand = (command, row) => {
  switch (command) {
    case 'handleRerun':
      handleRerun(row)
      break
    case 'handleAnalysis':
      handleAnalysis(row)
      break
    case 'handleSimilarity':
      handleSimilarity(row)
      break
  }
}

// 重新判题
const handleRerun = async (row) => {
  try {
    await ElMessageBox.confirm('确定要重新判题吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const response = await rejudgeSubmission(row.id)
    if (response.code === 200) {
      ElMessage.success('重新判题请求已提交')
      getList()
    } else {
      ElMessage.error(response.message || '重新判题失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('重新判题失败:', error)
      ElMessage.error('重新判题失败')
    }
  }
}

// 性能分析
const handleAnalysis = (row) => {
  ElMessage.info('性能分析功能开发中')
}

// 相似度检测
const handleSimilarity = (row) => {
  ElMessage.info('相似度检测功能开发中')
}

// 工具函数
const getStatusText = (status) => {
  const statusMap = {
    'ACCEPTED': '通过',
    'WRONG_ANSWER': '错误答案',
    'TIME_LIMIT_EXCEEDED': '超时',
    'MEMORY_LIMIT_EXCEEDED': '内存超限',
    'RUNTIME_ERROR': '运行错误',
    'COMPILE_ERROR': '编译错误',
    'SYSTEM_ERROR': '系统错误',
    'JUDGING': '判题中',
    'PENDING': '等待中'
  }
  return statusMap[status] || '未知'
}

const getStatusTagType = (status) => {
  const typeMap = {
    'ACCEPTED': 'success',
    'WRONG_ANSWER': 'danger',
    'TIME_LIMIT_EXCEEDED': 'warning',
    'MEMORY_LIMIT_EXCEEDED': 'warning',
    'RUNTIME_ERROR': 'danger',
    'COMPILE_ERROR': 'danger',
    'SYSTEM_ERROR': 'danger',
    'JUDGING': 'primary',
    'PENDING': 'info'
  }
  return typeMap[status] || 'info'
}

const getStatusClass = (status) => {
  const classMap = {
    'ACCEPTED': 'success',
    'WRONG_ANSWER': 'danger',
    'TIME_LIMIT_EXCEEDED': 'warning',
    'MEMORY_LIMIT_EXCEEDED': 'warning',
    'RUNTIME_ERROR': 'danger',
    'COMPILE_ERROR': 'danger',
    'SYSTEM_ERROR': 'danger',
    'JUDGING': 'primary',
    'PENDING': 'info'
  }
  return classMap[status] || 'info'
}

const getTestCaseStatusText = (status) => {
  return getStatusText(status)
}

const getTestCaseStatusTagType = (status) => {
  return getStatusTagType(status)
}

const getScoreClass = (score) => {
  if (!score) return ''
  if (score >= 90) return 'excellent'
  if (score >= 70) return 'good'
  if (score >= 60) return 'pass'
  return 'fail'
}

const formatMemory = (bytes) => {
  if (!bytes) return '0KB'
  if (bytes < 1024) return `${bytes}B`
  if (bytes < 1024 * 1024) return `${Math.round(bytes / 1024)}KB`
  return `${Math.round(bytes / (1024 * 1024))}MB`
}

const getFileExtension = (language) => {
  const extensionMap = {
    'java': 'java',
    'python': 'py',
    'cpp': 'cpp',
    'c': 'c',
    'javascript': 'js',
    'go': 'go'
  }
  return extensionMap[language] || 'txt'
}

const parseTime = (time, pattern = '{y}-{m}-{d} {h}:{i}:{s}') => {
  if (!time) return ''
  return time
}

// 页面加载
onMounted(() => {
  getList()
})
</script>

<style lang="scss" scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.text-muted {
  color: #909399;
  font-size: 12px;
}

.problem-title {
  font-weight: 500;
  color: #303133;
}

.score-text {
  font-weight: bold;

  &.excellent {
    color: #67c23a;
  }

  &.good {
    color: #409eff;
  }

  &.pass {
    color: #e6a23c;
  }

  &.fail {
    color: #f56c6c;
  }
}

.code-detail {
  .submission-info {
    margin-bottom: 20px;
  }

  .code-section {
    margin-bottom: 20px;

    h4 {
      margin-bottom: 12px;
      color: #303133;
      border-bottom: 1px solid #ebeef5;
      padding-bottom: 8px;
    }

    .code-container {
      background-color: #f5f7fa;
      border: 1px solid #dcdfe6;
      border-radius: 4px;
      padding: 16px;
      max-height: 400px;
      overflow-y: auto;

      pre {
        margin: 0;
        font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
        font-size: 14px;
        line-height: 1.5;
        white-space: pre-wrap;
        word-wrap: break-word;
      }
    }
  }

  .compile-section {
    h4 {
      margin-bottom: 12px;
      color: #303133;
      border-bottom: 1px solid #ebeef5;
      padding-bottom: 8px;
    }

    .compile-info {
      background-color: #fef0f0;
      border: 1px solid #fbc4c4;
      border-radius: 4px;
      padding: 12px;

      pre {
        margin: 0;
        font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
        font-size: 13px;
        color: #f56c6c;
        white-space: pre-wrap;
      }
    }
  }
}

.result-detail {
  .result-summary {
    margin-bottom: 24px;

    .stat-item {
      text-align: center;
      padding: 16px;
      background-color: #f5f7fa;
      border-radius: 8px;

      .stat-value {
        font-size: 20px;
        font-weight: bold;
        margin-bottom: 4px;

        &.success {
          color: #67c23a;
        }

        &.danger {
          color: #f56c6c;
        }

        &.warning {
          color: #e6a23c;
        }

        &.primary {
          color: #409eff;
        }

        &.info {
          color: #909399;
        }
      }

      .stat-label {
        color: #606266;
        font-size: 14px;
      }
    }
  }

  .testcase-results {
    h4 {
      margin-bottom: 16px;
      color: #303133;
      border-bottom: 1px solid #ebeef5;
      padding-bottom: 8px;
    }
  }
}

.dialog-footer {
  text-align: right;
}

// 分页组件样式
:deep(.el-pagination) {
  margin-top: 20px;
  text-align: right;
}
</style>
